/**
 *
 * Created by shenzaifang on 2019-04-09
 */

import formDownload from 'src/hrpub/common/utils/download/download';
import {getAppPageConfig} from 'src/hrpub/common/utils/utils';

let appConfig = getAppPageConfig();
if (new RegExp(/localhost:3006/g).test(window.location.href)) {
    appConfig.pagecode= '600920C0nccloud';
    appConfig.appcode= '600920C0';
}

// regdetail:带转正； dimidetail：离职明细； entrydetail：入职明细； chgdetail：变动明细； psndetail：员工明细
export const COMMON = {
    appConfig,
    pageInfo: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
        totalPage: 1
    }, // 主页面表格的分页信息
    pageMain: 'main', // 首页
    pageTotal: 'totle', // 详情页-总人数
    pageEntry: 'entry', // 详情页-入职人数
    pageDimission: 'dimission', // 详情页-离职人数
    pageChange: 'change', // 详情页-本月变动
    pageReg: 'reg', // 详情页-待转正人数
    pageAgeEdu: 'ageedu', // 详情页-年龄与学历结构
    pageEntryDimission: 'entrydimission', // 详情页-入离职趋势
    pageRankStr: 'rankstructure', // 详情页-职级结构
    pageStaffChange: 'staffchange', // 详情页-人员变动分析
    pageSubdetail: 'subdetail', // 详情页-穿透的详情页
    tableIdObj: {
        "totle": "psndetail",
        "entry": "entrydetail",
        "dimission": "dimidetail",
        "change": "chgdetail",
        "reg": "regdetail",
        "ageedu": "ageedudetail",
        "entrydimission": "entrydimidetail",
        "rankstructure": "rankstrudetail",
        "staffchange": "staffchangedetail",
        "subdetail": "psndetail"
    },
    exportUrl: {
        "totle": "/nccloud/hrtrn/companalysis/StaffInfoExportAction.do",
        "entry": "/nccloud/hrtrn/companalysis/EntryDetailsExportAction.do",
        "dimission": "/nccloud/hrtrn/companalysis/DimissionDetailsExportAction.do",
        "change": "/nccloud/hrtrn/companalysis/ChangeDetailsExportAction.do",
        "reg": "/nccloud/hrtrn/companalysis/StayPositiveDetailsExportAction.do",
        "ageedu": "/nccloud/hrtrn/companalysis/TalentStructureExportAction.do",
        "entrydimission": "/nccloud/hrtrn/companalysis/TalentFlowExportAction.do",
        "rankstructure": "/nccloud/hrtrn/companalysis/TalentStructureExportAction.do",
        "staffchange": "/nccloud/hrtrn/companalysis/TalentFlowExportAction.do"
    }
};

/**
 * 导出文件
 * @param postData
 * @param language
 * @param urlId
 * @param toast
 * @param url
 */
export function exportExcel(postData, language, urlId, toast, url) {

    postData.outfilename = 'sssss';
    postData.pk_org = postData.pk_org && typeof(postData.pk_org) !== 'string' && postData.pk_org.join(',') || postData.pk_org;
    postData.pk_psncl = postData.pk_psncl && typeof(postData.pk_psncl) !== 'string' && postData.pk_psncl.join(',') || postData.pk_psncl;
    formDownload({
        body: postData,
        url: url || COMMON.exportUrl[urlId],
        enctype: 2,
        onResult: (body) => {
            let res = JSON.parse(body.innerText);

            if (!res || res.success) {
                toast({
                    color: 'success',
                    content: language['gx6008-000187'] // 导出成功
                });
            } else {
                toast({
                    color: 'danger',
                    content: res.error.message // 导出失败
                });
            }
        }
    });
}

export function setStruTable(res, props, clickTable) {
    const {staffCom} = props;
    const {language} = staffCom;
    let tableId = COMMON.tableIdObj[staffCom.page];
    let tableMeta = {
        "items": [
            {
                "label": language["gx6008-000190"],// 组织名称
                "attrcode": "orgname",
                "visible": true
            }
        ],
        "moduletype": "table",
        "pagination": false,
        "code": tableId,
        "name": "年龄与学历结构"
    };
    let tableData = {
        areacode: tableId,
        rows: []
    };
    let data = res.data;
    if (!Array.isArray(data)) return;
    // 获取表头/表体数据
    data.forEach((dataItem, index) => {
        // 设置表格数据
        let rowItem = {
            status: "0",
            values: {
                "orgname": {
                    display: dataItem.orgname,
                    value: dataItem.orgname
                },
                "org_id": {
                    value: dataItem.org_id
                },
                "istotal": {
                    value: index === (data.length - 1)
                }
            }
        };
        tableData.rows.push(rowItem);
        if (dataItem.hasOwnProperty('age')) {
            let ageData = dataItem.age;
            if (index < 1) {
                let ageItem = {
                    "label": language["gx6008-000138"],// 年龄
                    "attrcode": "ageall",
                    "visible": true,
                    "children": []
                };
                tableMeta.items.push(ageItem);
                setTableHeader(ageData, ageItem, ageItem.attrcode, clickTable);
            }
            setRowItem(ageData, "ageall", rowItem.values);
        }
        if (dataItem.hasOwnProperty('edu')) {
            let eduData = dataItem.edu;
            if (index < 1) {
                let eduItem = {
                    "label": language["gx6008-000139"],// 学历
                    "attrcode": "eduall",
                    "visible": true,
                    "children": []
                };
                tableMeta.items.push(eduItem);
                setTableHeader(eduData, eduItem, eduItem.attrcode, clickTable);
            }
            setRowItem(eduData, "eduall", rowItem.values);
        }
        if (dataItem.hasOwnProperty('jobrank')) {
            let jobrankData = dataItem.jobrank;
            if (index < 1) {
                let jobrankItem = {
                    "label": language["gx6008-000185"],// 职级
                    "attrcode": "jobrankall",
                    "visible": true,
                    "children": []
                };
                tableMeta.items.push(jobrankItem);
                setTableHeader(jobrankData, jobrankItem, jobrankItem.attrcode, clickTable)
            }
            setRowItem(jobrankData, "jobrankall", rowItem.values);
        }
    });
    let template = props.meta.getMeta();
    template[tableId] = tableMeta;

    return new Promise(((resolve) => {
        props.meta.setMeta(template, () => {
            props.editTable.setTableData(tableId, tableData);
            resolve();
        });
    }))
}

export function setFlowTable(res, props, clickTable) {
    const {staffCom} = props;
    const {language} = staffCom;
    let tableId = COMMON.tableIdObj[staffCom.page];
    let tableMeta = {
        "items": [
            {
                "label": language["gx6008-000191"],// 月份
                "attrcode": "month",
                "visible": true
            }
        ],
        "moduletype": "table",
        "pagination": false,
        "code": tableId,
        "name": "月份"
    };
    let tableData = {
        areacode: tableId,
        rows: []
    };
    let data = res.data;
    if (!Array.isArray(data)) return;
    // 获取表头/表体数据
    data.forEach((dataItem, index) => {
        // 设置表格数据
        let rowItem = {
            status: "0",
            values: {
                "month": {
                    display: dataItem.month,
                    value: dataItem.month
                }
            }
        };
        tableData.rows.push(rowItem);
        if (dataItem.hasOwnProperty('change')) {
            let changeData = dataItem.change;
            if (index < 1) {
                let changeItem = {
                    "label": language["gx6008-000192"],// 变动
                    "attrcode": "changeall",
                    "visible": true,
                    "children": []
                };
                tableMeta.items.push(changeItem);
                setTableHeader(changeData, changeItem, changeItem.attrcode, clickTable);
            }
            setRowItem(changeData, "changeall", rowItem.values);
        }
        if (dataItem.hasOwnProperty('dimission')) {
            let dimissionData = dataItem.dimission;
            if (index < 1) {
                let dimissionItem = {
                    "label": language["gx6008-000076"],// 离职
                    "attrcode": "dimissionall",
                    "visible": true,
                    "children": []
                };
                tableMeta.items.push(dimissionItem);
                setTableHeader(dimissionData, dimissionItem, dimissionItem.attrcode, clickTable);
            }
            setRowItem(dimissionData, "dimissionall", rowItem.values);
        }
        if (dataItem.hasOwnProperty('entry')) {
            let entryData = dataItem.entry;
            if (index < 1) {
                let entryItem = {
                    "label": language["gx6008-000075"],// 入职
                    "attrcode": "entryall",
                    "visible": true,
                    "children": []
                };
                tableMeta.items.push(entryItem);
                setTableHeader(entryData, entryItem, entryItem.attrcode, clickTable)
            }
            setRowItem(entryData, "entryall", rowItem.values);
        }
    });
    let template = props.meta.getMeta();
    template[tableId] = tableMeta;

    return new Promise(((resolve) => {
        props.meta.setMeta(template, () => {
            props.editTable.setTableData(tableId, tableData);
            resolve();
        });
    }))
}

function setTableHeader(sourceData, metaData, code, clickFun) {
    if (!Array.isArray(sourceData)) return;
    sourceData.forEach((item, index) => {
        let key = code + index;
        // 设置表头
        metaData.children.push({
            "itemtype": "customer",
            "scale": "0",
            "maxlength": "28",
            "visible": true,
            "label": item.name,
            "disabled": true,
            "attrcode": key,
            "render": (text, record, index) => {
                return (
                    <a style={{
                        "cursor": 'pointer', "display": 'block',
                        "text-overflow": 'ellipsis',
                        "overflow": 'hidden',
                        "white-space": 'nowrap'
                    }}
                       onClick={() => {
                           clickFun && typeof clickFun === 'function' && clickFun(record, key)
                       }}
                    >
                        {record.values && record.values[key] && record.values[key].value || record[key] && record[key].value}
                    </a>
                );
            }
        })
    });
}

function setRowItem(sourceData, code, values) {
    if (!Array.isArray(sourceData)) return;
    sourceData.forEach((item, index) => {
        let key = code + index;

        values[key] = {
            value: item.count,
            values: {
                "key": code,
                ...item
            }
        }
    })
}

export function fixData(advObj, pageInfo) {

    if (advObj.org && typeof advObj.org !== "string") {
        advObj.org = advObj.org.refpk;
    }
    if (advObj.psncl && typeof advObj.psncl !== "string") {
        advObj.psncl = advObj.psncl.refpk;
    }
    if (advObj.pk_org && typeof advObj.pk_org !== "string") {
        advObj.pk_org = advObj.pk_org.refpk;
    }
    if (advObj.pk_psncl && typeof advObj.pk_psncl !== "string") {
        advObj.pk_psncl = advObj.pk_psncl.refpk;
    }
}
